﻿namespace Windows32
{
    using System;
    using System.Drawing;
    using System.Runtime.InteropServices;

    public abstract class GDIObject : IDisposable
    {
        protected IntPtr intHandle = IntPtr.Zero;

        protected GDIObject()
        {
        }

        protected int ColorToInt(Color color)
        {
            return (((color.B << 0x10) | (color.G << 8)) | color.R);
        }

        [DllImport("gdi32.dll", CharSet=CharSet.Auto)]
        private static extern int DeleteObject(IntPtr hObject);
        public virtual void Dispose()
        {
            if (this.intHandle.ToInt32() != 0)
            {
                DeleteObject(this.intHandle);
                this.intHandle = IntPtr.Zero;
            }
        }

        protected Color IntToColor(int color)
        {
            int b = (color >> 0x10) & 0xff;
            int g = (color >> 8) & 0xff;
            int r = color & 0xff;
            return Color.FromArgb(r, g, b);
        }

        [DllImport("gdi32.dll", CharSet=CharSet.Auto)]
        private static extern IntPtr SelectObject(IntPtr hDC, IntPtr hObject);
        public IntPtr SelectTo(int hdc)
        {
            return SelectObject(new IntPtr(hdc), this.intHandle);
        }

        public IntPtr SelectTo(IntPtr hdc)
        {
            return SelectObject(hdc, this.intHandle);
        }

        public bool UnSelect(int hdc, IntPtr handle)
        {
            return (SelectObject(new IntPtr(hdc), handle) == this.intHandle);
        }

        public bool UnSelect(IntPtr hdc, IntPtr handle)
        {
            return (SelectObject(hdc, handle) == this.intHandle);
        }

        public IntPtr Handle
        {
            get
            {
                return this.intHandle;
            }
        }
    }
}

